package com.alibaba.springbootrbac.service.impl;

import com.alibaba.springbootrbac.mapper.PermissionMapper;
import com.alibaba.springbootrbac.model.entity.Permission;
import com.alibaba.springbootrbac.model.entity.Role;
import com.alibaba.springbootrbac.model.param.permission.PermissionCreateParam;
import com.alibaba.springbootrbac.model.param.permission.PermissionPageQueryParam;
import com.alibaba.springbootrbac.model.param.permission.PermissionUpdateParam;
import com.alibaba.springbootrbac.service.PermissionService;
import com.alibaba.springbootrbac.utils.BizException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author ZhouYaDong
 * @date 2025/8/23
 * @description
 */
@Transactional(rollbackFor = Exception.class) // 表示出现任何异常都会回滚
@Service
public class PermissionServiceImpl implements PermissionService {

    @Resource
    private PermissionMapper permissionMapper;

    @Override
    public void addPermission(PermissionCreateParam param) {

        // 先判断权限名称是否已经存在
        Permission permission = permissionMapper.selectOne(new QueryWrapper<Permission>().eq("name", param.getName()));
        if (permission != null) {
            throw new BizException("权限名称已存在");
        }

        Permission permission1 = new Permission();
        permission1.setName(param.getName());
        permission1.setDescription(param.getDescription());
        int insert = permissionMapper.insert(permission1);
        if (insert == 0) {
            throw new BizException("新增权限失败");
        }
    }

    @Override
    public void updatePermission(PermissionUpdateParam param) {
        // 先判断权限名称是否已经存在
        Permission permission = permissionMapper.selectOne(new QueryWrapper<Permission>().eq("name", param.getName()));
        if (permission != null && !permission.getId().equals(param.getId())) {
            throw new BizException("权限名称已存在");
        }
        // 根据主键ID查询权限信息,获取当前数据version字段，进行乐观锁控制
        Permission permission1 = permissionMapper.selectById(param.getId());

        // 判断权限信息是否存在，防止空指针异常
        if (permission1 == null) {
            throw new BizException("权限信息不存在，ID：" + param.getId());
        }

        // 进行属性拷贝
        BeanUtils.copyProperties(param, permission1);

        // 执行更新操作
        int i = permissionMapper.updateById(permission1);

        if (i == 0) {
            throw new BizException("更新权限失败");
        }
    }

    @Override
    public void deletePermission(String id) {
        int i = permissionMapper.deleteById(id);
        if (i == 0) {
            throw new BizException("删除权限失败");
        }

    }

    @Override
    public IPage<Permission> getPermissionPageList(PermissionPageQueryParam param) {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();

        queryWrapper.like(StringUtils.hasText(param.getName()), "name", param.getName())
                .like(StringUtils.hasText(param.getDescription()), "description", param.getDescription())
                .ge(param.getStartCreateTime() != null, "create_time", param.getStartCreateTime())
                .le(param.getEndCreateTime() != null, "create_time", param.getEndCreateTime())
                .ge(param.getStartUpdateTime() != null, "update_time", param.getStartUpdateTime())
                .le(param.getEndUpdateTime() != null, "update_time", param.getEndUpdateTime())
                .orderByDesc("create_time");

        int pageNum = param.getPageNum() != null ? param.getPageNum() : 1;
        int pageSize = param.getPageSize() != null ? param.getPageSize() : 10;

        Page<Permission> page = new Page<>(pageNum, pageSize);
        return permissionMapper.selectPage(page, queryWrapper);
    }

    @Override
    public List<Permission> getPermissionsByUserId(String userId) {
        return permissionMapper.selectPermissionsByUserId(userId);
    }
}
